package com.lanhao.aot.baidu;

import org.apache.commons.lang3.tuple.Pair;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;

import cn.hutool.http.HttpRequest;

public class BaiduMapUtil {

	public static final String AK = "D57bb405f00f37748fa15011e6d63aac";

	public static String getCityByLocation(String lat, String lng) {
		JSONObject obj = getLocationInfo(lat, lng).getJSONObject("result").getJSONObject("addressComponent");
		return obj.getString("city");
	}

	public static JSONObject getLocationInfo(String lat, String lng) {
		String url = "https://api.map.baidu.com/geocoder/v2/?location=" + lat + "," + lng + "&output=json&ak=" + AK
				+ "&pois=0";
		String resp = HttpRequest.get(url).execute().body();
		JSONObject obj = JSON.parseObject(resp);
		return obj;
	}

	/**
	 * Pair<lng, lat>
	 * 
	 * @param ip
	 * @return
	 */
	public static final Pair<String, String> getLocationByIp(String ip) {
		String url = "http://gps.voiceads.cn/query?ip=" + ip;
		String resp = HttpRequest.get(url).execute().body();
		JSONObject obj = JSON.parseObject(resp);
		String lng = obj.getString("lon");
		String lat = obj.getString("lat");
		return Pair.of(lng, lat);
	}

	public static final String getCityByIp(String ip) {
		String url = "https://api.map.baidu.com/location/ip?ip=" + ip + "&ak=" + AK;
		String resp = HttpRequest.get(url).execute().body();
		if (StringUtils.isNotBlank(resp)) {
			JSONObject respObj = JSON.parseObject(resp);
			JSONObject contentObject = respObj.getJSONObject("content");
			if (contentObject != null) {
				JSONObject addressDetailObject = contentObject.getJSONObject("address_detail");
				if (addressDetailObject != null) {
					return addressDetailObject.getString("city");
				}
				return contentObject.getString("address");
			}
		}
		return resp;
	}


	public static void main(String[] args) {
//		System.out.println(getCityByLocation("28.694439", "115.939728"));
		System.out.println(getCityByIp("36.7.87.91"));
	}
}
